import MyIcon from '@/components/MyIcon';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getPosIDs, getTenantID } from '@/utils';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { GlobalShortcutContext } from '../mconfig';
import pageStyles from '@/common/pageLayout.less';
import { Col, Form, Input, message, Row, Spin, TreeSelect } from 'antd';
import { GlobalShortcutKeyAPI } from '../common/type';
import { addShortcutService, editShortcutService } from '../services';
import _ from 'lodash';

export const ShortcutUpdateModal: React.FC<
  GlobalShortcutKeyAPI.IShortcutUpdateModal
> = ({ onClose, open, shortcutType, shortcutItemObj }) => {
  /**
   * 弹框 ref
   */
  const shortcutModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (shortcutModalRef) {
      if (shortcutModalRef.current) {
        if (shortcutModalRef.current.onModalCancel) {
          shortcutModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 获取上下文共享数据
   */
  const { userInfoObj, reloadUserInfoRun, curRes } = useContext(
    GlobalShortcutContext,
  );

  /**
   * 创建表单
   */
  const [updateForm] = Form.useForm();

  /**
   * 保存 快捷键的图标
   */
  const [shortIconType, setShortIconType] = useState<string>('');

  /**
   * 递归菜单数据
   * @param data
   * @returns
   */
  const loopMenuList = (data: []): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        path: item?.url ?? item?.id,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
          >
            <a>
              <MyIcon type={item?.icon} />
            </a>
            <span style={{ marginLeft: 8 }}>{item?.name}</span>
          </div>
        ),
        value: item?.url ?? item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? loopMenuList(item?.children)
            : null,
        disabled: !!!item.pID,
        searchTitle: item?.name,
      };
    });
  };

  /**
   * 获取渲染的菜单数据
   */
  const treeData = useMemo(() => {
    return loopMenuList(
      userInfoObj?.paramObject?.[`${getPosIDs()}`]?.menuResourceList,
    );
  }, [userInfoObj]);

  /**
   * 选中快捷菜单
   * @param e
   * @param node
   */
  const onTreeSelect = (e: any, node: any) => {
    updateForm.setFieldsValue({
      shortcutName: node?.name,
    });
    setShortIconType(node?.icon);
  };

  /**
   * 是否拥有布局
   */
  const targetLayout = useMemo(() => {
    return userInfoObj?.muserLayoutList?.find((i: any) => {
      return (
        i?.layoutType === `${getTenantID()}10011000` &&
        i?.userPositionID == getPosIDs()
      );
    });
  }, [userInfoObj]);

  /**
   * 新增编辑后的回调
   */
  const updateShortcutCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadUserInfoRun();
      onCloseModal();
    } else {
      message.error(res?.msg);
    }
  };

  useEffect(() => {
    if (shortcutType == 'edit' && shortcutItemObj?.url) {
      updateForm?.setFieldsValue({
        url: shortcutItemObj?.url,
        shortcutName: shortcutItemObj?.shortcutName,
      });
    }
  }, [shortcutType, shortcutItemObj]);

  /**
   * 新增快捷方式
   */
  const { addShortcutLoading, addShortcutRun } = addShortcutService(
    updateShortcutCallback,
  );

  /**
   * 编辑快捷方式
   */
  const { editShortcutLoading, editShortcutRun } = editShortcutService(
    updateShortcutCallback,
  );

  const onSave = () => {
    updateForm?.validateFields()?.then((values: any) => {
      let layoutInfo: any[] =
        targetLayout?.layoutInfo && targetLayout?.layoutInfo?.length > 0
          ? _.cloneDeep(targetLayout?.layoutInfo)
          : [];
      let editLayout: any[] = [];
      if (shortcutType == 'add') {
        let isHasSameUrl = layoutInfo?.some((i: any) => i?.url == values?.url);
        if (isHasSameUrl) {
          message.warn('已存在相同快捷方式！');
          return;
        } else {
          let newLayoutObj: any = {
            ...values,
            id: values?.url,
            iconType: shortIconType,
          };
          layoutInfo?.push(newLayoutObj);
        }
      } else {
        layoutInfo?.forEach((item: any) => {
          let itemObj: any = {};
          if (item?.url == shortcutItemObj?.url) {
            itemObj = {
              ...values,
              id: values?.url,
              iconType: shortcutItemObj?.iconType,
            };
          } else {
            itemObj = { ...item };
          }
          editLayout?.push(itemObj);
        });
      }

      if (targetLayout && targetLayout?.id) {
        let editPayload: Record<string, any> = {
          layoutInfo: shortcutType == 'add' ? layoutInfo : editLayout,
          id: targetLayout?.id,
          versionNum: targetLayout?.versionNum,
        };
        editShortcutRun(editPayload);
      } else {
        addShortcutRun({
          layoutInfo: layoutInfo,
        });
      }
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={shortcutModalRef}
        title={shortcutType == 'add' ? '添加快捷方式' : '编辑快捷方式'}
        width={document.body.clientWidth * 0.2}
        onCancel={onClose}
        bodyStyle={{
          padding: '10px 0px',
        }}
        centered
        onOk={onSave}
        confirmLoading={addShortcutLoading || editShortcutLoading}
      >
        <Spin spinning={addShortcutLoading || editShortcutLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={updateForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name="url"
                    label="快捷菜单"
                    rules={[
                      {
                        required: true,
                        message: '请选择快捷菜单',
                      },
                    ]}
                  >
                    <TreeSelect
                      placeholder="请选择快捷菜单"
                      treeData={treeData}
                      onSelect={onTreeSelect}
                      showSearch={true}
                      treeNodeFilterProp={'searchTitle'}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="shortcutName"
                    label="快捷方式"
                    rules={[
                      {
                        required: true,
                        message: '请输入快捷方式名称',
                      },
                      {
                        max: 6,
                        message: '最多输入6个字符',
                      },
                    ]}
                  >
                    <Input
                      placeholder={'请输入快捷方式名称'}
                      // onChange={(e) => setTitle(e.target?.value)}
                      allowClear
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
